package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.LogUtil;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.ocs.diameter.message.*;
import org.simpleframework.http.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 费用查询接口
 * @author lwq
 *
 */
public class ReturnBalanceInfoDetailHandle2 implements IAsynCallHandler {
	
	private static final Logger _log = LoggerFactory.getLogger(ReturnBalanceInfoDetailHandle2.class);
	private PrintStream printStream;
	private JSONObject jsonContent;
	private UserResourceConfigService userResourceConfigService ;
    private long startTime;
    private Request request;

    public ReturnBalanceInfoDetailHandle2(PrintStream printStream, JSONObject jsonContent, Request request, long startTime) {
		this.printStream = printStream;
		this.jsonContent = jsonContent;
        this.startTime = startTime;
        this.request = request;
	}

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		
		try {
			String respXML = convertResponseString((Message) response, callParam.getServiceResultCode());

			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
//			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
//				MessageDetail detail = new MessageDetail();
//				detail.setBusinessCallId(callParam.getBussinessCallId());
//				detail.setSessionId(callParam.getSessionId());
//				detail.setServiceContextId(callParam.getServiceContextId());
//				detail.setMessageType(MessageType.WSA);
//				detail.setDetails(ack.getDATA());
//				detail.setMsgTime(new Date(ack.getMsgTime()));
//				detail.setOpType("send");
//				detail.setHostId(callParam.getUserName());
//				MessageDetailCacheManager.getInstance().add(detail);
//			}
            //记录到日志
            LogUtil.saveLogToABM(request,respXML,startTime);
			TaskManager.taskProcess(callParam);
            _log.info("http response(returnBalanceInfoDetail) " + respXML);

		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg=" + e.getMessage());
		}
	}

	
	
	/**
	 * 从Message中解析出需要的数据，并拼接成json字符串
	 * @param answer
	 * @param serviceResultCode
	 * @return
	 */
	private String convertResponseString(Message answer, int serviceResultCode) {
		_log.info("ReturnBalanceInfoDetailHandle2 serviceResultCode = {}", serviceResultCode);
		Gson gson = new Gson();
		// 返回json字符串最外层的map
		Map<String, Object> data = new HashMap<String, Object>();
		if(11202 == serviceResultCode || answer == null ) {
			data.put("resultCode", "-1");
			data.put("resultMsg", "查询失败");
            String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
            data.put("resultCode", newCode);
			return gson.toJson(data);
		}
		// 从下游解析返回信息中解析出来的数据，该数据和用户需要的数据并不相符，需要进行处理
		Map<String, Object> avpResultMap = getAvpsFromMessage(answer);
		
		if (null == avpResultMap) {
			data.put("resultCode", "-1");
			data.put("resultMsg", "查询失败");
			return gson.toJson(data);
		}else if(serviceResultCode != 0){
			// 如果返回了错误码，则将错误信息转给用户
            data.put("resultCode", serviceResultCode+"");
            data.put("resultMsg", "查询失败");
		}else{
            _log.info("=========================总流程最后一步 二段=====================");
			// json字符串中的returnPlanDetInfo节点，该节点为list
			List<Map<String, Object>> returnPlanDetInfoList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> list = (List<Map<String, Object>>)avpResultMap.get("ReturnPlanDetailInfos");
			if(list != null){
				for(Map<String, Object> one : list){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("returnPlanId", Long.valueOf((String)one.get("ReturnPlanId")));
					map.put("returnPlanName", one.get("ReturnPlanName"));
					map.put("returnFlag", one.get("ReturnFlag"));
					map.put("startTime", one.get("StartTime"));
					map.put("endTime", one.get("End_Time"));
					map.put("stateDate", one.get("StateDate"));
					map.put("returnBalance", Long.valueOf((String)one.get("PayAmount")));
					map.put("accNbr", one.get("AccNbrDetail"));
                    map.put("state", "00A");
					returnPlanDetInfoList.add(map);
				}
				data.put("resultCode", "0");
				data.put("resultMsg", "SUCCESS");
				data.put("returnPlanDetInfo", returnPlanDetInfoList);
			}else {
				data.put("resultCode", "-1");
				data.put("resultMsg", "查询失败");
			}
			
		}
        String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
        data.put("resultCode", newCode);
		return gson.toJson(data);
	}

	
	
	
	/**
	 * 从返回信息中解析AVP信息
	 * @param answer
	 * @return 解析信息出现异常返回null
	 */
	public Map<String, Object> getAvpsFromMessage(Message answer) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, String>> returnPlanDetailInfos = new ArrayList<Map<String, String>>();
		
		try {
			AVP serviceINformationAVP = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
			AVP_Grouped serviceInfomationGroup;
			serviceInfomationGroup = new AVP_Grouped(serviceINformationAVP);
			AVP[] avps = serviceInfomationGroup.queryAVPs();
			for(AVP avp : avps){
				if(avp.code() == 20631 && avp.vendorID() == 81000){
					// Result节点
					resultMap.put("Result", String.valueOf(new AVP_Unsigned32(avp).queryValue()));
				}else if(avp.code() == 80407 && avp.vendorID() == 81000){
					// Para_Field_Result节点
					resultMap.put("Para_Field_Result", String.valueOf(new AVP_UTF8String(avp).queryValue()));
				}else if(avp.code() == 90215 && avp.vendorID() == 81000){
					// ReturnPlanDetailInfo节点，下游返回信息中会有多个该节点
					Map<String, String> map = new HashMap<String, String>();
					map.put("ReturnPlanId", "");
					map.put("ReturnPlanName", "");
					map.put("ReturnFlag", "");
					map.put("StartTime", "");
					map.put("End_Time", "");
					map.put("StateDate", "");
					map.put("PayAmount", "");
					map.put("BalanceTypeFlag", "");
					map.put("AccNbrDetail", "");
					// 返还计划实例ID
					AVP_Grouped returnPlanDetailInfoGroup = new AVP_Grouped(avp);
					AVP ReturnPlanId = returnPlanDetailInfoGroup.find(90204, Constants.DIAMETER_VENDOR_CT);
					if (ReturnPlanId != null) {
						map.put("ReturnPlanId", new AVP_UTF8String(ReturnPlanId).queryValue());
					}
					// 返还计划名称
					AVP ReturnPlanName = returnPlanDetailInfoGroup.find(90206, Constants.DIAMETER_VENDOR_CT);
					if (ReturnPlanName != null) {
						map.put("ReturnPlanName", new AVP_UTF8String(ReturnPlanName).queryValue());
					}
					// 返还类型：0预存返还、1赠送返还
					AVP ReturnFlag = returnPlanDetailInfoGroup.find(90213, Constants.DIAMETER_VENDOR_CT);
					if (ReturnFlag != null) {
						map.put("ReturnFlag", String.valueOf(new AVP_Integer32(ReturnFlag).queryValue()));
					}
					// 状态时间（入账时间）
					AVP StateDate = returnPlanDetailInfoGroup.find(80419, Constants.DIAMETER_VENDOR_CT);
					if (StateDate != null) {
						map.put("StateDate", new AVP_UTF8String(StateDate).queryValue());
					}
					// 生效时间
					AVP StartTime = returnPlanDetailInfoGroup.find(5073, Constants.DIAMETER_VENDOR_CT);
					if (StartTime != null) {
						map.put("StartTime", new AVP_UTF8String(StartTime).queryValue());
					}
					// 失效时间
					AVP End_Time = returnPlanDetailInfoGroup.find(5075, Constants.DIAMETER_VENDOR_CT);
					if (End_Time != null) {
						map.put("End_Time", new AVP_UTF8String(End_Time).queryValue());
					}
					// 支付金额（分）,入账金额
					AVP PayAmount = returnPlanDetailInfoGroup.find(80196, Constants.DIAMETER_VENDOR_CT);
					if (PayAmount != null) {
						map.put("PayAmount", String.valueOf(new AVP_Integer64(PayAmount).queryValue()));
					}
					// 余额类型标识：0通用余额、1专用余额
					AVP BalanceTypeFlag = returnPlanDetailInfoGroup.find(90208, Constants.DIAMETER_VENDOR_CT);
					if (BalanceTypeFlag != null) {
						map.put("BalanceTypeFlag", String.valueOf(new AVP_Integer32(BalanceTypeFlag).queryValue()));
					}
					// 号码信息
					AVP AccNbrDetail = returnPlanDetailInfoGroup.find(90226, Constants.DIAMETER_VENDOR_CT);
					if (AccNbrDetail != null) {
						map.put("AccNbrDetail", new AVP_UTF8String(AccNbrDetail).queryValue());
					}
					returnPlanDetailInfos.add(map);
				}
			}
			resultMap.put("ReturnPlanDetailInfos", returnPlanDetailInfos);
		} catch (InvalidAVPLengthException e) {
			resultMap = null;
			_log.error("getAvpsFromMessage is error：", e);
		}
		return resultMap;
	}
	/**
	 * 由于计费侧提供的接口协议没变，只是地址调整，割接到3.0的本地网需要调用新的地址
	 * 集团电子发票API接口调整
	 * 获取判断使用的地址
	 * jf3_flag 刷新开关  配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
	 * Jf3_jt_latn_id  割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）
	 * resultLanIdStr 区域编码
	 * cityId
	 * jf3_jt_latn_id 是84201这种
		jf3_latn_id是1001 1018 这种
		jf3_area_coee是027 0716 这种
		type 传参0 1001类 传1 84210类   返参 1 新 0 旧的
	 */
	private String getVersionType(String cityId,String type) {
		String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
		String jf3_jt_latn_id = userResourceConfigService.getValue("jf3_jt_latn_id","");
		String jf3_latn_id = userResourceConfigService.getValue("jf3_latn_id","");
		String str;
		if("0".equals(type)) {
			//1001类型
			str = jf3_latn_id;
		}else {
			//84201 类型
			str = jf3_jt_latn_id;
		}
		//1 新流程  0 旧的流程
		if("1".equals(jf3_flag)) {
			if("888".equals(str)) {
				return "1";//新的
			}else {
				String[] split_jt_latn_id = str.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(cityId)) {
						//包含,仅区分新旧
						return "1";//新的 Recharged.jf3@027.ctnbc-bon.net
					}
				}
			}
			
		}
		return "0";//旧的 SeverRecharge.SGWPAY@027.ctnbc-bon.net  
	}

}
